﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApplication
{
    /// <summary>
    /// 阻塞队列[.net 4.0 貌似自带了阻塞队列]
    /// </summary>
    public class BlockQueue<T>
    {
        public readonly int SizeLimit = 0;
        private Queue<T> _queue = null;
        public int Count
        {
            get { return _queue.Count; }
        }
        private ManualResetEvent _enqueueWait = null;
        private ManualResetEvent _dequeueWait = null;
        public BlockQueue(int sizeLimit)
        {
            this.SizeLimit = sizeLimit;
            this._queue = new Queue<T>(this.SizeLimit);
            this._enqueueWait = new ManualResetEvent(false);
            this._dequeueWait = new ManualResetEvent(false);
        }
        /// <summary>
        /// 将对象添加到对象的结尾处。
        /// </summary>
        /// <param name="item"></param>
        public void EnQueue(T item)
        {
            if (this._IsShutdown == true) throw new InvalidCastException("Queue was shutdown. Enqueue was not allowed.");
            while (true)
            {
                lock (this._queue)
                {
                    if (this._queue.Count < this.SizeLimit)
                    {
                        this._queue.Enqueue(item);
                        this._enqueueWait.Reset();
                        this._dequeueWait.Set();
                        break;
                    }
                }
                this._enqueueWait.WaitOne();
            }
        }
        /// <summary>
        /// 移除并返回位于队列开始处的对象。
        /// </summary>
        /// <returns></returns>
        public T DeQueue()
        {
            while (true)
            {
                if (this._IsShutdown == true)
                {
                    lock (this._queue) return this._queue.Dequeue();
                }
                lock (this._queue)
                {
                    if (this._queue.Count > 0)
                    {
                        T item = this._queue.Dequeue();
                        this._dequeueWait.Reset();
                        this._enqueueWait.Set();
                        return item;
                    }
                }
                this._dequeueWait.WaitOne();
            }
        }
        private bool _IsShutdown = false;
        public void Shutdown()
        {
            this._IsShutdown = true;
            this._dequeueWait.Set();
        }
    }
}
